package com.java.controller.wx;

import com.java.bean.*;
import com.java.exception.DuplicateIdCardException;
import com.java.exception.DuplicatePhoneException;
import com.java.mvc.ResponseBody;
import com.java.service.CourierService;
import com.java.service.UserService;
import com.java.service.impl.CourierServiceImpl;
import com.java.service.impl.UserServiceImpl;
import com.java.util.*;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @ClassName UserController
 * @Description 微信用户控制
 * @Author 0715-YuHao
 * @Date 2020/9/15 16:14
 * @Version 1.0
 */
public class UserController {

    UserService userService = new UserServiceImpl();
    CourierService courierService = new CourierServiceImpl();

    @ResponseBody("/wx/loginSms.do")
    public String sendSms(HttpServletRequest request, HttpServletResponse response) {
        String userPhone = request.getParameter("userPhone");
        Message message = new Message();
//        String code = RandomCodeUtil.getCode();
//        boolean sms = SMSUtil.loginSMS(userPhone, code);
        String code = "111111";
        boolean sms = true;
        if (sms) {
            message.setStatus(0);
            message.setContent("验证码已发送，请查收！");
        }else {
            message.setStatus(-1);
            message.setContent("验证码发送失败，请检查手机号或稍后再试！");
        }
        UserUtil.setLoginSms(request.getSession(), userPhone, code);
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        ServletContext application = request.getServletContext();
        HttpSession session = request.getSession();
        List<String> loginList = (ArrayList<String>) application.getAttribute("loginList");
        if (loginList == null) {
            loginList = new ArrayList<>();
        }
        Message message = new Message();
        String userPhone = request.getParameter("userPhone");
        String username = null;
        if (loginList.contains(userPhone)) {
            message.setStatus(-1);
            message.setContent("用户已登录，请勿重新登录");
        }else {
            String userCode = request.getParameter("code");
            String sysCode = UserUtil.getLoginSms(request.getSession(), userPhone);
            if (sysCode == null) {
                message.setStatus(-1);
                message.setContent("你输入的手机号码未获取短信");
            }else {
                if (sysCode.equals(userCode)) {
                    Courier courier = courierService.findByPhone(userPhone);
                    if (courier != null) {
                        message.setStatus(0);
                        UserUtil.setUserInfo(session, 0);
                        message.setContent("登录成功！");
                        courierService.updateLoginTime(userPhone);
                        username = courier.getName();
                        if (username != null) {
                            session.setAttribute("username", username);
                        }
                        session.removeAttribute(userPhone);
                        session.setAttribute("userPhone", userPhone);
                        loginList.add(userPhone);
                        application.setAttribute("loginList", loginList);
                        Cookie cookie = new Cookie("userPhone", userPhone);
                        cookie.setMaxAge(60 * 60 * 24 * 7);
                        response.addCookie(cookie);
                    }else {
                        User user = userService.findByPhone(userPhone);
                        if (user != null) {
                            message.setStatus(0);
                            UserUtil.setUserInfo(session, 1);
                            message.setContent("登录成功！");
                            userService.updateLoginTime(userPhone);
                            username = user.getNickName();
                            if (username != null) {
                                session.setAttribute("username", username);
                            }
                            session.removeAttribute(userPhone);
                            session.setAttribute("userPhone", userPhone);
                            loginList.add(userPhone);
                            application.setAttribute("loginList", loginList);
                            Cookie cookie = new Cookie("userPhone", userPhone);
                            cookie.setMaxAge(60 * 60 * 24 * 7);
                            response.addCookie(cookie);
                        }else {
                            try {
                                boolean flag = userService.signUp(userPhone);
                                if (flag) {
                                    message.setStatus(0);
                                    message.setContent("注册成功！");
                                    UserUtil.setUserInfo(session, 1);
                                    userService.updateLoginTime(userPhone);
                                    session.setAttribute("userPhone", userPhone);
                                    session.removeAttribute(userPhone);
                                    loginList.add(userPhone);
                                    application.setAttribute("loginList", loginList);
                                    Cookie cookie = new Cookie("userPhone", userPhone);
                                    cookie.setMaxAge(60 * 60 * 24 * 7);
                                }else {
                                    message.setStatus(-1);
                                    message.setContent("注册失败！");
                                }
                            } catch (DuplicatePhoneException e) {
                                message.setStatus(-1);
                                message.setContent("手机号已注册，请直接登录！");
                            }
                        }
                    }
                }else {
                    message.setStatus(-1);
                    message.setContent("验证码不一致,请检查输入！");
                }
            }
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/login2.do")
    public String login2(HttpServletRequest request, HttpServletResponse response) {
        ServletContext application = request.getServletContext();
        HttpSession session = request.getSession();
        List<String> loginList = (ArrayList<String>) application.getAttribute("loginList");
        if (loginList == null) {
            loginList = new ArrayList<>();
        }
        String userPhone = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie:cookies) {
            if (cookie.getName().equals("userPhone")) {
                userPhone = cookie.getValue();
            }
        }
        Message msg = new Message();
        if (loginList.contains(userPhone)) {
            session.setAttribute("userPhone", userPhone);
            msg.setStatus(0);
        }else {
            msg.setStatus(-1);
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/userInfo.do")
    public String userInfo(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        int userInfo = UserUtil.getUserInfo(session);
        String userPhone = UserUtil.getUserPhone(session);
        String username = UserUtil.getUserName(session);
        Message message = new Message();
        Map<String, String> data = new HashMap<>();
        message.setStatus(userInfo);
        if (username != null) {
            message.setContent("欢迎" + username);
            data.put("username", username);
        }else {
            message.setContent("欢迎" + userPhone);
        }
        data.put("userPhone", userPhone);
        message.setData(data);
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/userStatus.do")
    public String userStatus(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String userPhone = request.getParameter("userPhone");
        Message message = new Message();
        User user = userService.findByPhone(userPhone);
        message.setStatus(user.getStatus());
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/getUserInfo.do")
    public String getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        int type = Integer.parseInt(request.getParameter("type"));
        String userPhone = request.getParameter("userPhone");
        Message message = new Message();
        String showPhone = userPhone.substring(0, 3) + "****" + userPhone.substring(7, 11);
        if (type == 0) {
            Courier courier = courierService.findByPhone(userPhone);
            String idCard = courier.getIdCard();
            String showIdCard = idCard.substring(0, 6) + "*******" + idCard.substring(13, 18);
            BootStrapTableCourier showCourier = new BootStrapTableCourier(
                    courier.getId(),
                    courier.getName(),
                    showPhone,
                    showIdCard,
                    "******",
                    courier.getNumberDispatch(),
                    "已激活",
                    DateFormatUtil.formatDate(courier.getSignUpTime()),
                    DateFormatUtil.formatDate(courier.getLoginTime())
            );
            message.setStatus(0);
            message.setData(showCourier);
        }else {
            User user = userService.findByPhone(userPhone);
            String idCard = user.getIdCard();
            String showIdCard = idCard.substring(0, 6) + "*******" + idCard.substring(12, 18);
            BootStrapTableUser showUser = new BootStrapTableUser(
                    user.getId(),
                    user.getNickName(),
                    showPhone,
                    showIdCard,
                    "******",
                    "已激活",
                    DateFormatUtil.formatDate(user.getSignUpTime()),
                    DateFormatUtil.formatDate(user.getLoginTime())
            );
            message.setStatus(0);
            message.setData(showUser);
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/getUserInfo2.do")
    public String getUserInfo2(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String userPhone = UserUtil.getUserPhone(session);
        Message message = new Message();
        if (UserUtil.getUserInfo(session) == 0) {
            Courier courier = courierService.findByPhone(userPhone);
            message.setStatus(0);
            message.setData(courier);
        }else {
            User user = userService.findByPhone(userPhone);
            message.setStatus(1);
            message.setData(user);
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/logout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        ServletContext application = request.getServletContext();
        ArrayList<String> loginList = (ArrayList<String>) application.getAttribute("loginList");
        String userPhone =UserUtil.getUserPhone(session);
        if (userPhone != null) {
            session.invalidate();
            loginList.remove(userPhone);
            application.setAttribute("loginList", loginList);
            Cookie cookie = new Cookie("userPhone", userPhone);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        return JSONUtil.toJSON(new Message(0));
    }

    @ResponseBody("/wx/verified.do")
    public String verified(HttpServletRequest request, HttpServletResponse response) {
        String nickName = request.getParameter("nickName");
        String phone = request.getParameter("phone");
        String idCard = request.getParameter("idCard");
        String password = request.getParameter("password");
        Message message = new Message();
        try {
            boolean insert = userService.updateByPhone(phone, new User(nickName, idCard, password));
            if (insert) {
                message.setStatus(0);
                message.setContent("注册成功");
            }else {
                message.setStatus(-1);
                message.setContent("注册失败");
            }
        } catch (DuplicateIdCardException e) {
            message.setStatus(-1);
            message.setContent("身份证已被注册！");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/userUpdate.do")
    public String update(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String name = request.getParameter("name");
        session.setAttribute("username", name);
        String password = request.getParameter("password");
        String userPhone = request.getParameter("userPhone");
        Message message = new Message();
        String userCode = request.getParameter("code");
        String sysCode = UserUtil.getLoginSms(session, userPhone);
        int type = UserUtil.getUserInfo(session);
        if (sysCode == null) {
            message.setStatus(-1);
            message.setContent("你输入的手机号码未获取短信");
        }else{
            if (sysCode.equals(userCode)) {
                if (type == 0) {
                    courierService.updateByWx(userPhone, new Courier(name, password, userPhone));
                }else {
                    userService.updateByWx(userPhone, new User(name, password, userPhone));
                }
                session.removeAttribute(userPhone);
                message.setStatus(0);
                message.setContent("修改成功");
            }else {
                message.setStatus(-1);
                message.setContent("验证码不一致,请检查输入！");
            }
        }
        return JSONUtil.toJSON(message);
    }
}
